package org.dyndns.opendemogroup.optimizer.operations;

import java.util.Random;

import org.dyndns.opendemogroup.optimizer.IOperation;
import org.dyndns.opendemogroup.optimizer.IOptimizationProblem;
import org.dyndns.opendemogroup.optimizer.Member;

/**
 * For each child, randomly picks alleles from either parent.
 */
public class RandomParentAlleleCrossover implements IOperation
{

	/**
	 * @see IOperation#perform(java.util.Random, IOptimizationProblem, Member,
	 *      Member, Member, Member)
	 */
	public void perform ( Random randomSource, IOptimizationProblem problem,
			Member parentOne, Member parentTwo, Member childOne, Member childTwo )
	{
		final int memberSize = parentOne.getMemberSize ( );
		populateChild ( randomSource, parentOne, parentTwo, memberSize,
			childOne );
		populateChild ( randomSource, parentOne, parentTwo, memberSize,
			childTwo );
	}

	/**
	 * Convenience method that crosses the two Member parents by taking alleles
	 * from both at random for each position.
	 * 
	 * @param randomSource
	 *        The source of randomness.
	 * @param parentOne
	 *        The first parent.
	 * @param parentTwo
	 *        The second parent.
	 * @param memberSize
	 *        The number of alleles in the genome.
	 * @param child
	 *        The Member to create.
	 */
	static void populateChild ( Random randomSource, Member parentOne,
			Member parentTwo, final int memberSize, Member child )
	{
		for ( int i = 0; i < memberSize; i++ )
		{
			final boolean coin = randomSource.nextBoolean ( );
			if ( coin )
			{
				child.genome[i] = parentOne.genome[i];
			}
			else
			{
				child.genome[i] = parentTwo.genome[i];
			}
		}
	}

}
